package com.uchonor.api.core.service;

import com.uchonor.api.core.entity.InterfaceConfig;
import com.uchonor.api.core.entity.InterfaceParameterConfig;
import com.uchonor.api.core.template.AbstractTemplateEngine;
import com.uchonor.olight.agent.annotation.Service;
import com.uchonor.olight.agent.utils.AssertUtils;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.ssssssss.magicapi.core.model.ApiInfo;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SaveSingleTableLowCodeApi extends LowCodeApi {

    @Override
    public boolean isSupper(String interfaceType) {
        return "SAVE_SINGLE_TABLE".equals(interfaceType);
    }

    public SaveSingleTableLowCodeApi(ResourceService resourceService, AbstractTemplateEngine abstractTemplateEngine) {
        super(resourceService, abstractTemplateEngine);
    }

    private List<InterfaceParameterConfig> getParameterList(String type, Map<String, List<InterfaceParameterConfig>> interfaceParameterMap) {
        List<InterfaceParameterConfig> parameterList = interfaceParameterMap.get(type);
        return parameterList.stream().filter(it -> StringUtils.isNotBlank(it.getDbColumn())).collect(Collectors.toList());
    }

    @Override
    public void generateScriptCode(ApiInfo magicEntity, Map<String, Object> dataMap) throws TemplateException, IOException {
        ClassPathResource classPathResource = new ClassPathResource("templates/ftl/singletable/save.ftl");
        Map<String, Object> templateMap = new HashMap<>();
        templateMap.put("magicEntity", magicEntity);
        // 过滤出所有请求中有数据库对应字段的类型
        Map<String, List<InterfaceParameterConfig>> interfaceParameterMap = getGroupInterfaceParameterConfigList((List<InterfaceParameterConfig>) dataMap.get("interfaceParameterConfig"));
        List<InterfaceParameterConfig> requestBodyParameterList = getParameterList("requestBody", interfaceParameterMap);
        templateMap.put("requestBodyParameterList", requestBodyParameterList);
        AssertUtils.notEmpty(requestBodyParameterList, "没有对应的数据库字段信息");
        // 获得主键
        InterfaceParameterConfig parameterConfig = requestBodyParameterList.stream().filter(it -> "1".equals(it.getDbPk())).findFirst().orElse(null);
        templateMap.put("pkParameterConfig", parameterConfig);
        InterfaceConfig interfaceConfig = (InterfaceConfig) dataMap.get("interfaceConfig");
        templateMap.put("tableName", interfaceConfig.getTableName());
        templateMap.put("datasourceKey", interfaceConfig.getDatasourceKey());
        templateMap.put("isUpdateBlank", "1".equals(interfaceConfig.getIsUpdateBlank()));
        magicEntity.setScript(abstractTemplateEngine.getTemplateStr(templateMap, classPathResource.getPath()));
    }
}
